package org.xt.module.admin;

import java.util.Date;

import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.xt.constants.Const;
import org.xt.constants.Res;
import org.xt.entity.Department;

@IocBean
@At("/admin/department")
public class DepartmentAdminModule {
	@Inject
	private Dao dao;
	@At("/add")
	@GET
	@Ok("jsp:admin.department.add")
	public void add(){
		//
	}
	
	@At("/add")
	@POST
	@Ok("json")
	public Res add(@Param("..")Department department){
		department.setCreateTime(new Date());
		department.setUpdateTime(new Date());
		try{
			department = dao.insert(department);
			if(department != null){
				return Res.NEW().code(Res.SUCCESS).msg("哇塞，添加成功了耶。。。").data(department);
			}else{
				return Res.NEW().code(Res.ERROR).msg("嚯嚯，没有添加成功咧。。。");
			}
		}catch(Exception e){
			if(e.getMessage().contains("Violation of UNIQUE KEY constraint")){
				return Res.NEW().code(Res.ERROR).msg("呀，这个部门已经有了，别重复添加勒。。。");
			}else{
				return Res.NEW().code(Res.ERROR).msg("额。。。后台系统异常，要不再来一次。。。");
			}
		}
	}
	
	@At("/update")
	@POST
	@Ok("json")
	public Res update(int id, String name){
		Department department = dao.fetch(Department.class, id);
		if(department == null){
			return Res.NEW().code(Res.ERROR).msg("额。。。更新失败了");
		}
		department.setUpdateTime(new Date());
		department.setName(name);
		try{
			if(dao.update(department) > 0){
				return Res.NEW().code(Res.SUCCESS).msg("当地格朗，更新成功了").data(department);
			}else{
				return Res.NEW().code(Res.ERROR).msg("哇哇哇，更失败了");
			}
		}catch(Exception e){
			return Res.NEW().code(Res.ERROR).msg("额。。。后台系统异常，要不再来一次。。。");
		}
	}
	
	@At("/delete")
	@POST
	@Ok("json")
	public Res delete(int id){
		try{
			if(dao.delete(Department.class, id) > 0){
				return Res.NEW().code(Res.SUCCESS).msg("删了都");
			}else{
				return Res.NEW().code(Res.ERROR).msg("昂，删掉了0条");
			}
		}catch(Exception e){
			return Res.NEW().code(Res.ERROR).msg("额。。。后台系统异常，要不再来一次。。。");
		}
	}
	
	@At("/list")
	@GET
	@Ok("jsp:admin.department.list")
	public void list(){
		
	}
	
	@At("/list")
	@POST
	@Ok("json")
	public Res list(@Param(value="page", df="1")int page, @Param(value="size", df="10")int size){
		Pager pager = dao.createPager(page, size);
		return Res.NEW().code(Res.SUCCESS).msg("获取部门成功").data(dao.query(Department.class, null, pager));
	}
}
